package com.shenmazong.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: server-java-demo
 * @description: ThreadVolatileTest1
 * @author: 亮子说编程
 * @create: 2020-10-20 10:14
 **/

class BuyTicketRunable implements Runnable {

    public static Integer ticketCount = 100;

    @Override
    public void run() {

        ThreadVolatileTest1.lock.lock();
        try {
            if (ticketCount > 0) {
                System.out.println(Thread.currentThread().getName() + ",ticketCount2=" + ticketCount);
                ticketCount--;
            }
        }
        finally {
            ThreadVolatileTest1.lock.unlock();
        }


    }
}

public class ThreadVolatileTest1 {

    public static Lock lock;

    public static void main(String[] args) throws InterruptedException {

        //--1 创建锁
        lock = new ReentrantLock();

        for (int idx = 0; idx < 200; idx++) {
            new Thread(new BuyTicketRunable()).start();
        }

        Thread.sleep(1000*2);

        System.out.println(Thread.currentThread().getName()+",ticketCount="+BuyTicketRunable.ticketCount);
    }
}
